package com.light.roller;

import java.util.ArrayList;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.extension.input.touch.controller.MultiTouch;
import org.anddev.andengine.extension.input.touch.controller.MultiTouchController;
import org.anddev.andengine.extension.input.touch.controller.MultiTouchException;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.input.touch.detector.ScrollDetector;
import org.anddev.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener;
import org.anddev.andengine.input.touch.detector.SurfaceScrollDetector;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.content.Intent;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.KeyEvent;

import com.badlogic.gdx.math.Vector2;
import com.huw.cameramanagers.CameraManager;
import com.huw.debuger.Debugger;
import com.huw.debuger.FileIO;
import com.huw.debuger.FileIO.FileName;
import com.light.buttons.ActionButton;
import com.light.buttons.Button;
import com.light.buttons.Button.ButtonState;
import com.light.buttons.ExitButton;
import com.light.buttons.JumpButton;
import com.light.buttons.LeftButton;
import com.light.buttons.RightButton;
import com.light.gamecomponents.FormAnimatedButton;
import com.light.gamecomponents.FormButton;
import com.light.gamecomponents.FormRunningText;
import com.light.gamecomponents.GameForm;
import com.light.gamecomponents.LevelText;
import com.light.gamecomponents.physics.RollerPhysicsWorld;
import com.light.music.BackGroundMusicController;

public class Roller extends BaseGameActivity implements IOnSceneTouchListener, SensorEventListener, IScrollDetectorListener, IUpdateHandler{
	
	public static enum RollerState { MENU, STAGE_CHOOSING, STAGE, GAMEOVER, PAUSE };
	protected static enum BlackScreenAction { NEXT_STAGE, RESET, MENU,NONE }
	protected BlackScreenAction blackScreenAction = BlackScreenAction.NONE;
		
	public static final double GSENSOR_SENSITIVITY = 0;
	public static final int CAMERA_WIDTH = 720;
	public static final int CAMERA_HEIGHT = 480;
	public static final Vector2 SettingCameraPosition = new Vector2 (-11000,-11000);
	public Vector2 InitializeCameraPosition;
	
	/* The categories. */
	public static final short CATEGORYBIT_NORMAL = 0x01;
	public static final short CATEGORYBIT_BAR_HOLDER = 0x02;
	public static final short CATEGORYBIT_WALL = 0x04;
	public static final short CATEGORYBIT_BAR = 0x08;
	public static final short CATEGORYBIT_CAMERA = 0x16;

	/* And what should collide with what. */
	public static final short MASKBIT_NORMAL = CATEGORYBIT_NORMAL|CATEGORYBIT_WALL|CATEGORYBIT_BAR;
	public static final short MASKBIT_BAR_HOLDER = CATEGORYBIT_BAR;
	public static final short MASKBIT_WALL = CATEGORYBIT_NORMAL ;
	public static final short MASKBIT_BAR = CATEGORYBIT_BAR_HOLDER | CATEGORYBIT_NORMAL | CATEGORYBIT_BAR;
	public static final short MASKBIT_CAMERA = CATEGORYBIT_CAMERA;
	
	//
	public static final Vector2 mainHeadSize = new Vector2(24,22);
	public static final Vector2 mainBodySize = new Vector2(17,8);
	public static final Vector2 mainHand1Size = new Vector2(12,15);
	public static final Vector2 mainHand2Size = new Vector2(14,15);
	public static final Vector2 mainLeg1Size = new Vector2(17,20);
	public static final Vector2 mainLeg2Size = new Vector2(21,14);

	public static Direction nowDirection = Direction.UP;
	public static RollerState state = RollerState.MENU;
	public static Menu menu;
	public static Camera camera;
	public static CameraManager cameraManager;
	public ArrayList<Vector2> CameraVertexList = null;
	public static Debugger debugger;
	public static int orientation;
	
	protected static SurfaceScrollDetector mScrollDetector;
	protected static RollerPhysicsWorld physicsWorld;
	protected static Scene scene;
	
	public PhysicsWorld getPhysicWorld() { return physicsWorld; }
	
	public static Player player;

	// For Sensors
	
	protected static SensorManager sensorManager;
	public static SensorEvent sensorEvent;
	public SensorManager getSensorManager() { return sensorManager; }
	
	// For AnalogController	
	// For Buttons
	
	public static JumpButton jumpButton;
	public static ActionButton actionButton;
	public static RightButton rightButton;
	public static LeftButton leftButton;
	public static ExitButton exitButton;	
	public static GameForm form;
	public static GameForm hintForm;
	public static LevelText levelText;
	//public static ChooseStageButton chooseStageButton;
	
	// For Stage

	public static Stage stage;
	
	protected Direction m_initializeDirection;
	
	public static int CurrentNum = 1;
	public static int PreNum = 0;
	final public static int StageNum =29;
	
	protected int stageID = 1;
	
	public static boolean playMusic = true;
	
	Display getOrient;
	
	@Override
    public void onCreate(Bundle savedInstanceState) 
	{
        super.onCreate(savedInstanceState);
        
        getOrient = getWindowManager().getDefaultDisplay();
        
        orientation = getOrient.getOrientation();

       if (orientation == Configuration.ORIENTATION_SQUARE)
    	   orientation = Configuration.ORIENTATION_PORTRAIT;
       else if (orientation == Configuration.ORIENTATION_UNDEFINED)
    	   orientation = Configuration.ORIENTATION_LANDSCAPE;
        //{

	        //Configuration config = getResources().getConfiguration();
	        //orientation = config.orientation;
	
	       // if(orientation == Configuration.ORIENTATION_UNDEFINED)
	       // {
		       // if(getOrient.getWidth() == getOrient.getHeight())
			   //     orientation = Configuration.ORIENTATION_PORTRAIT;
		       // else
			   // 
				    //if (getOrient.getWidth() > getOrient.getHeight())
				    //	orientation = Configuration.ORIENTATION_PORTRAIT;
				    //else
				    //    orientation = Configuration.ORIENTATION_LANDSCAPE;
				    
			//    
        
        sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        debugger = new Debugger(this,camera,player);
		System.gc();
    }
	
	static public String getStageName(int num)
	{
		
		if(num>=1&&num<=10)return BigMenuWorld1.getStageNameArray()[num-1];
		if(num>=11&&num<=20)return BigMenuWorld2.getStageNameArray()[(num % 11)];
		if(num>=21&&num<=30)return BigMenuWorld3.getStageNameArray()[(num % 21)];
		return "Undefined Stage Name";
	}
	
    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
        state = RollerState.MENU;
        
        if (FileIO.LoadGame(this, FileName.Volume) >= 1)
        {
        	BackGroundMusicController.setVolume(1);
        	playMusic = true;
        }
        else
        {
        	BackGroundMusicController.setVolume(0);
        	playMusic = false;
        }
        	
        BackGroundMusicController.Play();
    }
	
	@Override
	public Engine onLoadEngine() {
		camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
		Engine engine = new Engine(engineOptions);
        
		return engine;
	}
	
	public Engine initialize(Vector2 cameraCenter, Vector2 playerInitialPositon, Vector2 DoorPosition, Direction initialDirection)
	{

        cameraCenter.y += 80;
        cameraCenter.x += 20;
        
        InitializeCameraPosition = new Vector2(cameraCenter.x,cameraCenter.y);
        
		camera = new Camera(SettingCameraPosition.x, 
							SettingCameraPosition.y, 
	                        CAMERA_WIDTH, 
	                        CAMERA_HEIGHT);
		
		final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
		engineOptions.setNeedsSound(true);
		engineOptions.setNeedsMusic(true);
		Engine engine = new Engine(engineOptions);
		
		try {
			if(MultiTouch.isSupported(this)) {
				engine.setTouchController(new MultiTouchController());
				if(MultiTouch.isSupportedDistinct(this)) {
					
				} else {
					//this.mPlaceOnScreenControlsAtDifferentVerticalLocations = true;
				}
			} else {

			}
		} catch (final MultiTouchException e) {
		}
		engineOptions.getTouchOptions().setRunOnUpdateThread(true);
        player = new Player(this, playerInitialPositon, initialDirection);
        jumpButton = new JumpButton(this, player);
        actionButton = new ActionButton(this, player, stage);
        form = new GameForm(this, new Vector2(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2));
        hintForm = new GameForm(this, new Vector2(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2));
        exitButton = new ExitButton(this, form, initialDirection);
        rightButton = new RightButton(this, player);
        leftButton = new LeftButton(this, player);      
        levelText = new LevelText(this, null, null, null);
        m_initializeDirection = initialDirection;
        //chooseStageButton = new ChooseStageButton(this, 200,200,Roller_2.class);

        cameraManager = new CameraManager(this, player, camera,InitializeCameraPosition,DoorPosition);     
      
        
        return engine;
	}

	@Override
	public void onLoadResources() {
        clearAllG8Stuff();
		debugger.onLoadResources();
		player.onLoadResources();
		jumpButton.onLoadResources();
		exitButton.onLoadResources();
		actionButton.onLoadResources();
		stage.onLoadResources();
		cameraManager.onLoadResources();
		rightButton.onLoadResources();
		leftButton.onLoadResources();
		levelText.onLoadResources();
		int offsetX = 50;
		int offsetY = 47;
		int formButtonX = 55;
		FormRunningText textTemp = new FormRunningText(this, new Vector2(20, 20));
		hintForm.addRunningText(textTemp, new Vector2(25 + offsetX, 45 + offsetY));
		hintForm.onLoadResources();
		

		FormButton temp = new FormButton("BackToMenu", 
						                 this,
						                 new Vector2(formButtonX + offsetX + 15, 10 + offsetY)) {
			@Override
			public void whenClicked() {	
				preSwitchToMenu(); 
				//FileIO.SaveGame(m_game,1);
				//FileIO.LoadGame(m_game);
				}
		};
		
		form.addButton(temp, new Vector2(formButtonX + offsetX + 15, 10 + offsetY));		
		temp = new FormButton("ReturnButton",
		          			  this,
		          			  new Vector2(formButtonX + offsetX - 30, 68 + offsetY)) {
			@Override
			public void whenClicked() 
			{ 
				form.hideForm();
				ungreyButton();
				unpause();
	
			}
		};

		form.addButton(temp, new Vector2(formButtonX + offsetX - 30, 68 + offsetY));
		
		temp = new FormButton("ResetButton",
    			  			  this,
    			  			  new Vector2(formButtonX + offsetX - 5, 130 + offsetY)) {
			@Override
			public void whenClicked() { preReset(); }
		};
			
		form.addButton(temp, new Vector2(formButtonX + offsetX - 5, 130 + offsetY));
		
		temp = new FormAnimatedButton("SoundButton",
	  			  			  		  this,
	  			  			  		  new Vector2(330, 210)) {
			@Override
			public void onLoadScene(Scene scene, PhysicsWorld physicsWrold)
			{
				super.onLoadScene(scene, physicsWrold);
				if (FileIO.LoadGame(m_game, FileName.Volume) >= 1)
				{
					m_sprite.setCurrentTileIndex(0);
					m_clicked = true;
				}
				else
				{
					m_sprite.setCurrentTileIndex(1);
					m_clicked = false;
				}
			}
			
			@Override
			public void whenClicked() {
				if (m_clicked)
				{
					m_clicked = false;
					m_sprite.setCurrentTileIndex(1);
					BackGroundMusicController.setVolume(0);
					playMusic = false;
					FileIO.SaveVolume(m_game, 0);
				}
				else
				{
					m_clicked = true;
					m_sprite.setCurrentTileIndex(0);
					BackGroundMusicController.setVolume(1);
					playMusic = true;
					FileIO.SaveVolume(m_game, 1);

				}
			}
		};

		form.addButton(temp, new Vector2(330, 210));
			
		form.onLoadResources();
		
	}

	@Override
	public Scene onLoadScene() {
		this.mEngine.registerUpdateHandler(new FPSLogger());
		this.scene = new Scene(2);		
		scene.setBackground(new ColorBackground(0, 0, 0));
		this.mScrollDetector = new SurfaceScrollDetector(this);
		mScrollDetector.setEnabled(true);
		
		scene.setOnSceneTouchListener(this);
		scene.setTouchAreaBindingEnabled(true);
		if (Roller.physicsWorld != null)
		{
			Roller.physicsWorld.dispose();
		}
		Roller.physicsWorld = new RollerPhysicsWorld(30, new Vector2(0, 0), false, 3, 2);
		scene.registerUpdateHandler(Roller.physicsWorld);		
		player.setStage(stage);

		stage.onLoadScene(scene, physicsWorld);
		player.onLoadScene(scene, physicsWorld);
		hintForm.onLoadScene(scene, physicsWorld);
	    jumpButton.onLoadScene(scene, physicsWorld);
	    rightButton.onLoadScene(scene, physicsWorld);
	    leftButton.onLoadScene(scene, physicsWorld);
	    actionButton.onLoadScene(scene, physicsWorld);
	    exitButton.onLoadScene(scene, physicsWorld);
	    form.onLoadScene(scene, physicsWorld);
		cameraManager.onLoadScene(scene, physicsWorld);
		debugger.onLoadScene(scene, physicsWorld);
		levelText.onLoadScene(scene, physicsWorld);
		
		//chooseStageButton.onLoadScene(scene, physicsWorld);
		
		physicsWorld.registerUpdateHandler(player);
		physicsWorld.registerUpdateHandler(cameraManager);
		physicsWorld.registerUpdateHandler(jumpButton);
		physicsWorld.registerUpdateHandler(actionButton);
		physicsWorld.registerUpdateHandler(leftButton);
		physicsWorld.registerUpdateHandler(exitButton);
		physicsWorld.registerUpdateHandler(rightButton);
		physicsWorld.registerUpdateHandler(levelText);
	
		scene.registerUpdateHandler(this);
		//physicsWorld.registerUpdateHandler(chooseStageButton);
		
			
		
		
		return scene;
	}

	@Override
	public void onLoadComplete() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) 
	{
		debugger.onSceneTouchEvent(pScene, pSceneTouchEvent);
		cameraManager.onSceneTouchEvent(pScene, pSceneTouchEvent);
		mScrollDetector.onTouchEvent(pSceneTouchEvent);			
		return true;
	}	
	
	@Override
	public void onScroll(final ScrollDetector pScollDetector, final TouchEvent pTouchEvent, float pDistanceX, final float pDistanceY) 
	{
		cameraManager.onScroll(pScollDetector, pTouchEvent, pDistanceX, pDistanceY);
	}


	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
		
	}

	protected boolean checkedForFirstTime = false;
	@Override
	public void onSensorChanged(SensorEvent event) {
		if (state != RollerState.PAUSE)
		{
			sensorEvent = event;
			if (actionButton != null && actionButton.getState() == Button.ButtonState.CONTROLABLE)
			{
				float[] accelerometer_values = sensorEvent.values.clone();
		    	if (orientation == Configuration.ORIENTATION_PORTRAIT)
		    	{
		    		//debugger.showText("ORIENTATION_PORTRAIT");
			    	if (Math.abs(accelerometer_values[1]) >= Math.abs(accelerometer_values[0]))
			    	{
			    		if (accelerometer_values[1] <= -GSENSOR_SENSITIVITY)
			    		{
			    			actionButton.changePicture(Direction.LEFT);
			    			//debugger.showText("Direction.LEFT");
			    		}
			    		else if (accelerometer_values[1] > GSENSOR_SENSITIVITY)
			    		{
			    			actionButton.changePicture(Direction.RIGHT);
			    			//debugger.showText("Direction.RIGHT");
			    		}
			    	}
			    	else
			    	{
			    		if (accelerometer_values[0] <= -GSENSOR_SENSITIVITY)
			    		{
			    			actionButton.changePicture(Direction.DOWN);
			    			//debugger.showText("Direction.DOWN");
			    		}
			    		else if (accelerometer_values[0] > GSENSOR_SENSITIVITY)
			    		{
			    			actionButton.changePicture(Direction.UP);
			    			//debugger.showText("Direction.UP");
			    		}
			    	}
		    	}
		    	else if (orientation == Configuration.ORIENTATION_LANDSCAPE)
		    	{
		    		//debugger.showText("ORIENTATION_LANDSCAPE");
		    		if (Math.abs(accelerometer_values[1]) >= Math.abs(accelerometer_values[0]))
			    	{
			    		if (accelerometer_values[1] <= -GSENSOR_SENSITIVITY)
			    		{
			    			actionButton.changePicture(Direction.DOWN);
			    			//debugger.showText("Direction.DOWN");
			    		}
			    		else if (accelerometer_values[1] > GSENSOR_SENSITIVITY)
			    		{
			    			actionButton.changePicture(Direction.UP);
			    			//debugger.showText("Direction.UP");
			    		}
			    	}
			    	else
			    	{
			    		if (accelerometer_values[0] <= -GSENSOR_SENSITIVITY)
			    		{
			    			actionButton.changePicture(Direction.RIGHT);
			    			//debugger.showText("Direction.RIGHT");
			    		}
			    		else if (accelerometer_values[0] > GSENSOR_SENSITIVITY)
			    		{
			    			actionButton.changePicture(Direction.LEFT);
			    			//debugger.showText("Direction.LEFT");
			    		}
			    	}
		    	}
			}
		}
	}
	
	@Override
    protected void onStop() {
    	sensorManager.unregisterListener(this);
    	ResourceManager.unLoadAllSounds();
    	ResourceManager.onStop();
        super.onStop();
    }

	public void stageSwitchToMenu()
	{
		ResourceManager.unLoadAllSounds();
		this.finish();
		if (Roller.CurrentNum >= 1 && Roller.CurrentNum <= 10)
			this.startActivity(new Intent(this, BigMenuWorld1.class));
		else if (Roller.CurrentNum >= 11 && Roller.CurrentNum <= 20)
			this.startActivity(new Intent(this, BigMenuWorld2.class));
		else if (Roller.CurrentNum >= 21 && Roller.CurrentNum <= 30)
			this.startActivity(new Intent(this, BigMenuWorld3.class));
		else
			this.startActivity(new Intent(this, Launcher.class));
		BufferObjectManager.getActiveInstance().clear();
	}	
	
	public void switchToNextStage()
	{
		
		Roller.CurrentNum++;
		FileIO.SaveGame(this, Roller.CurrentNum);
		
		nextStageSetting();
	}
	
	public void clearAllG8Stuff()
	{
		ResourceManager.unLoadAllSounds();
		ResourceManager.clear(this);
		stage.removeStoper(scene, physicsWorld);
	}
	
	protected void nextStageSetting()
	{
		
	}
	
	public void stageSwitch(Class<?> switchStage)
	{

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	     if (keyCode == KeyEvent.KEYCODE_BACK)
	     {
	    	 if(Debugger.JUMP_STAGE)switchToNextStage();
	    	 return true;
	     }
	     else if (keyCode == KeyEvent.KEYCODE_HOME)
	     	 return true;
	     else if (keyCode == KeyEvent.KEYCODE_MENU)
	    	 return true;
	     else if (keyCode == KeyEvent.KEYCODE_SEARCH)
	    	 return true;
	     
	     return super.onKeyDown(keyCode, event);    
	}
	
	public void preSwitchToMenu()
	{
		Roller.PreNum = CurrentNum;
		cameraManager.CameraLightOff();
		blackScreenAction = BlackScreenAction.MENU;
		
	}
	
	public void preReset()
	{
		Roller.PreNum = CurrentNum;
		cameraManager.CameraLightOff();
		blackScreenAction = BlackScreenAction.RESET;
	}
	
	public void preSwitchToNextStage()
	{
		
		Roller.PreNum = CurrentNum;
		cameraManager.CameraLightOff();
		blackScreenAction = BlackScreenAction.NEXT_STAGE;
	}
	
	public void reset()
	{		
		
		ResourceManager.unLoadAllSounds();
		this.finish();
		this.startActivity(new Intent(this, Roller_1.class));
		
	}
	@Override
	protected void onPause() {
	    super.onPause(); 
	    BackGroundMusicController.pause(); 
	}
	public void pause()
	{
		state = RollerState.PAUSE;
		jumpButton.setState(ButtonState.NOT_CONTROLABLE);
		rightButton.setState(ButtonState.NOT_CONTROLABLE);
		leftButton.setState(ButtonState.NOT_CONTROLABLE);
		actionButton.setState(ButtonState.NOT_CONTROLABLE);
		
		physicsWorld.pause();
	}
	
	public void unpause()
	{
		state = RollerState.STAGE;
		jumpButton.setState(ButtonState.CONTROLABLE);
		rightButton.setState(ButtonState.CONTROLABLE);
		leftButton.setState(ButtonState.CONTROLABLE);
		actionButton.setState(ButtonState.CONTROLABLE);
		physicsWorld.unpause();
	}
	
	public void initializeDirection()
	{
		jumpButton.initializeDirection(m_initializeDirection);
		actionButton.initializeDirection(m_initializeDirection);
		rightButton.initializeDirection(m_initializeDirection);
		leftButton.initializeDirection(m_initializeDirection);
		exitButton.initializeDirection(m_initializeDirection);
		hintForm.initializeDirection(m_initializeDirection);
		form.initializeDirection(m_initializeDirection);
		player.initializeDirection(m_initializeDirection);
		switch (m_initializeDirection)
		{
		case UP:
			physicsWorld.setGravity(new Vector2(0, SensorManager.GRAVITY_EARTH));
			nowDirection = Direction.UP;
			break;
		case DOWN:
			physicsWorld.setGravity(new Vector2(0, -SensorManager.GRAVITY_EARTH));
			nowDirection = Direction.DOWN;
			break;
		case LEFT:
			physicsWorld.setGravity(new Vector2(-SensorManager.GRAVITY_EARTH, 0));
			nowDirection = Direction.LEFT;
			break;
		case RIGHT:
			physicsWorld.setGravity(new Vector2(SensorManager.GRAVITY_EARTH, 0));
			nowDirection = Direction.RIGHT;
			break;
		}
	}
	
	public void hideButton()
	{
		jumpButton.hideButton();
		actionButton.hideButton();
		rightButton.hideButton();
		leftButton.hideButton();
	}
	public void greyButton()
	{
		jumpButton.greyButton();
		rightButton.greyButton();
		leftButton.greyButton();
	}
	public void ungreyButton()
	{
		jumpButton.ungreyButton();
		rightButton.ungreyButton();
		leftButton.ungreyButton();
	}
	
	
	public void changeDirection()
	{
		/*
		for (Body tempBody : physicsWorld.getBodies())
		{
			if (tempBody.getType() == BodyType.DynamicBody && 
				tempBody != player.getBody())
			{

				
				tempBody.setAwake(true);
				PhysicsComponents.somethingBad = true;
				tempBody.setActive(false);
				tempBody.setActive(true);
				for (Fixture temFix : tempBody.getFixtureList())
				{
					if (player.m_isInAirD.contains(temFix))
						player.m_isInAirD.remove(temFix);
					if (player.m_isInAirU.contains(temFix))
						player.m_isInAirU.remove(temFix);
					if (player.m_isInAirL.contains(temFix))
						player.m_isInAirL.remove(temFix);
					if (player.m_isInAirR.contains(temFix))
						player.m_isInAirR.remove(temFix);
				}
			}
			
		}
		*/
		jumpButton.onSensorChanged(sensorEvent);
		actionButton.onSensorChanged(sensorEvent);
		rightButton.onSensorChanged(sensorEvent);
		leftButton.onSensorChanged(sensorEvent);
		exitButton.onSensorChanged(sensorEvent);
		hintForm.onSensorChanged(sensorEvent);
		form.onSensorChanged(sensorEvent);
		player.onSensorChanged(sensorEvent);
		if (physicsWorld != null)
		{
	    	float[] accelerometer_values = sensorEvent.values.clone();
	    	if (orientation == Configuration.ORIENTATION_PORTRAIT)
	    	{
		    	if (Math.abs(accelerometer_values[1]) >= Math.abs(accelerometer_values[0]))
		    	{
		    		if (accelerometer_values[1] <= -GSENSOR_SENSITIVITY && 
		    			physicsWorld.getGravity().x != -SensorManager.GRAVITY_EARTH)
		    		{
		    			physicsWorld.setGravity(new Vector2(-SensorManager.GRAVITY_EARTH, 0));
		    			nowDirection = Direction.LEFT;
		    		}
		    		else if (accelerometer_values[1] > GSENSOR_SENSITIVITY && physicsWorld.getGravity().x != SensorManager.GRAVITY_EARTH)
		    		{
		    			physicsWorld.setGravity(new Vector2(SensorManager.GRAVITY_EARTH, 0));
		    			nowDirection = Direction.RIGHT;
		    		}
		    	}
		    	else
		    	{
		    		if (accelerometer_values[0] <= -GSENSOR_SENSITIVITY && physicsWorld.getGravity().y != -SensorManager.GRAVITY_EARTH)
		    		{
		    			physicsWorld.setGravity(new Vector2(0, -SensorManager.GRAVITY_EARTH));
		    			nowDirection = Direction.DOWN;
		    		}
		    		else if (accelerometer_values[0] > GSENSOR_SENSITIVITY && physicsWorld.getGravity().y != SensorManager.GRAVITY_EARTH)
		    		{
		    			physicsWorld.setGravity(new Vector2(0, SensorManager.GRAVITY_EARTH));
		    			nowDirection = Direction.UP;
		    		}
		    	}
	    	}
	    	else 
	    	{
	    		if (Math.abs(accelerometer_values[1]) >= Math.abs(accelerometer_values[0]))
		    	{
		    		if (accelerometer_values[1] <= -GSENSOR_SENSITIVITY && 
		    			physicsWorld.getGravity().y != -SensorManager.GRAVITY_EARTH)
		    		{
		    			physicsWorld.setGravity(new Vector2(0, -SensorManager.GRAVITY_EARTH));
		    			nowDirection = Direction.DOWN;
		    		}
		    		else if (accelerometer_values[1] > GSENSOR_SENSITIVITY && 
		    				 physicsWorld.getGravity().y != SensorManager.GRAVITY_EARTH)
		    		{
		    			physicsWorld.setGravity(new Vector2(0, SensorManager.GRAVITY_EARTH));
		    			nowDirection = Direction.UP;
		    		}
		    	}
		    	else
		    	{
		    		if (accelerometer_values[0] <= -GSENSOR_SENSITIVITY && 
		    			physicsWorld.getGravity().x != SensorManager.GRAVITY_EARTH)
		    		{
		    			physicsWorld.setGravity(new Vector2(SensorManager.GRAVITY_EARTH, 0));
		    			nowDirection = Direction.RIGHT;
		    		}
		    		else if (accelerometer_values[0] > GSENSOR_SENSITIVITY && 
		    				 physicsWorld.getGravity().x != -SensorManager.GRAVITY_EARTH)
		    		{
		    			physicsWorld.setGravity(new Vector2(-SensorManager.GRAVITY_EARTH, 0));
		    			nowDirection = Direction.LEFT;
		    		}
		    	}
	    	}
		}
	}
	

	boolean cameraMovingChecked = false;

	@Override
	public void onUpdate(float pSecondsElapsed) {		

		
		if (cameraManager.isLightOff())
		{
			
			switch (blackScreenAction)
			{
			case NEXT_STAGE:
				//debugger.showText("NEXT_STAGE");
				blackScreenAction = BlackScreenAction.NONE;
				switchToNextStage();
				break;
			case RESET:
				//debugger.showText("RESET");
				blackScreenAction = BlackScreenAction.NONE;
				reset();
				break;
			case NONE:
				//debugger.showText("NONE");
				break;
			case MENU:
				blackScreenAction = BlackScreenAction.NONE;
				stageSwitchToMenu();
			default:
				//debugger.showText("WTF");
				break;
			}
		}
		else if(!cameraMovingChecked&&cameraManager.isLightOn())
		{
			if(Roller.PreNum==Roller.CurrentNum)this.exitButton.changeToMenu();
			cameraMovingChecked = true;
		} 
		else BackGroundMusicController.Play();
		
	}
	public void hideGreyButton()
	{
		leftButton.hideGreyButton();
		rightButton.hideGreyButton();
		jumpButton.hideGreyButton();
	}
	
	public void buttonPositionReset()
	{
		leftButton.initializeDirection(nowDirection);
		rightButton.initializeDirection(nowDirection);
		jumpButton.initializeDirection(nowDirection);
		actionButton.initializeDirection(nowDirection);
	}
	
}